package com.yiwenup.leetcode.offer;

import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/
 **/
public class No058 {
    /**
     * 执行用时：1 ms, 在所有 Java 提交中击败了100.00%的用户
     * 内存消耗：38.2 MB, 在所有 Java 提交中击败了63.58%的用户
     */
    public String reverseWords(String s) {
        String[] words = s.split(" ");
        StringBuilder sb = new StringBuilder();
        int n = words.length - 1;
        for (int i = n; i > 0; i--) {
            if (words[i].equals("")) continue;
            sb.append(words[i]).append(" ");
        }
        if (!words[0].equals("")) sb.append(words[0]);

        return sb.toString();
    }

    /**
     * 执行用时：2 ms, 在所有 Java 提交中击败了91.17%的用户
     * 内存消耗：38.6 MB, 在所有 Java 提交中击败了13.33%的用户
     */
    public String reverseWords2(String s) {
        Stack<String> stack = new Stack<>();
        String[] words = s.trim().split(" ");
        StringBuilder sb = new StringBuilder();

        int length = words.length;
        for (String word : words) {
            if (!word.equals("")) {
                stack.push(word);
            }
        }

        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }

        return sb.toString().trim();
    }
}
